/**
 * 
 */
package cn.ad.server.common.utils.monitor;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import cn.ad.server.common.utils.monitor.impl.DefaultCallPoint;
import cn.ad.server.common.utils.monitor.impl.DefaultTransaction;
import cn.ad.server.common.utils.monitor.impl.TransactionCompleTrigger;


/**
 * @author Wu Chengjun
 *
 */
public class Catcher implements TransactionCompleTrigger{

	private static Logger LOGGER = LogManager.getLogger("monitor");
	
	private static Map<String, Transaction> transactions;
	
	private static Catcher _instance = new Catcher();
	
	private Catcher(){
		transactions = new ConcurrentHashMap<>();
	}
	
	
	private static Catcher getInstance(){
		return _instance;
	}
	
	public static Transaction newTransaction(String name){
		DefaultTransaction t = new DefaultTransaction(name);
		transactions.put(Thread.currentThread().getName(), t);
		t.setCompleteTrigger(getInstance());
		return t;
	}
	
	public static CallPoint newCallPoint(String className, String methodName){
		CallPoint c = new DefaultCallPoint(className, methodName);
		logCallPoint(c);
		return c;
	}
	
	public static void logCallPoint(String className, String method, long duration){
		Transaction t = transactions.get(Thread.currentThread().getName());
		if(t != null){
			DefaultCallPoint cp = new DefaultCallPoint(className, method);
			t.addChild(cp);
		}
	}

	public static void logCallPoint(CallPoint callPoint){
		Transaction t = transactions.get(Thread.currentThread().getName());
		if(t != null){
			t.addChild(callPoint);
		}
	}

	@Override
	public void trigger(Transaction t) {
		transactions.remove(Thread.currentThread().getName());
		loggerTransaction(t);
	}
	
	private void loggerTransaction(Transaction t){
		LOGGER.info(t.toString());
	}
}
